<script setup lang="ts">
import type { Organization } from '@/api/organization/type'
import type { FormInstance } from 'element-plus'
import { orgTree } from '@/api/organization'
import { Refresh } from '@element-plus/icons-vue'

const queryFormRef = ref(ElForm)
const updateDialogVisible = ref(false)
const isDisabled = ref(true)
const loading = ref(false)
const orgList = ref<Organization[]>([])
const tableRef = ref()

const updateDialogName = ref('新增用户')
// 刷新
function refreshUser() {

}
const updateFormRef = ref<FormInstance>()
const updateFormData = reactive<Organization>({
  name: '',
})
const refresh: Organization = {
  name: '',
}
const updateRules = computed(() => ({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入联系号码', trigger: 'blur' },
  ],
}))
// 保存更新入口
function handleExecute(formEl: FormInstance | any) {
  if (updateFormData.id) {
    handleUpdate(formEl)
  }
  else {
    handleSave(formEl)
  }
}
// 保存
async function handleSave(formEl: FormInstance | any) {
  if (!formEl)
    return
  const isValid = await formEl.validate()
  if (!isValid)
    return
  ElMessageBox.confirm(
    '确认是否新增',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    Object.assign(updateFormData, refresh)
  }).catch(() => ElMessage.info('新增取消'))
}

// 更新
async function handleUpdate(formEl: FormInstance | any) {
  if (!formEl)
    return
  const isValid = await formEl.validate()
  if (!isValid)
    return
  ElMessageBox.confirm(
    '确认是否修改',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    Object.assign(updateFormData, refresh)
  }).catch(() => ElMessage.info('修改取消'))
}

// 加载查询
onMounted(() => {
  getTree()
})

function getTree() {
  orgTree().then((result) => {
    orgList.value = result
  })
}

// 控制自动展开状态
const shouldExpand = ref(false)

// 查询条件
const orgSearch = reactive<Organization>({
  id: undefined,
  name: '',
})

// 查询
const handleQuery = computed(() => {
  if (!orgSearch.name?.trim() && orgSearch.id === undefined && orgSearch.id === null)
    return orgList.value
  return filterTree(orgList.value, orgSearch)
})

// 递归过滤函数
function filterTree(data: Organization[], keyword: Organization): Organization[] {
  return data
    .map(item => ({ ...item })) // 浅拷贝避免污染原始数据
    .filter((item) => {
      // 保留匹配项或其子节点匹配的父级
      let isMatch1 = true
      if (keyword.name && item.name) {
        isMatch1 = item.name.toLowerCase().includes(keyword.name)
      }
      let isMatch2 = true
      if (keyword.id && item.id) {
        isMatch2 = item.id === Number(keyword.id)
      }

      if (item.children) {
        // 递归过滤子节点
        const children = filterTree(item.children, keyword)
        item.children = children.length > 0 ? children : undefined
      }
      return (isMatch1 && isMatch2) || (item.children && item.children.length > 0)
    })
}

// 文本高亮函数
function highlightText(text: string): string {
  if (!orgSearch.name)
    return text
  const regex = new RegExp(`(${escapeRegExp(orgSearch.name)})`, 'gi')
  return text.replace(regex, '<span class="highlight">$1</span>')
}

// 转义正则特殊字符
function escapeRegExp(str: string): string {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

// 触发自动展开逻辑
function handleFilterChange() {
  shouldExpand.value = Boolean(orgSearch.name?.trim()) || Boolean(orgSearch.id)
}

// 重置
function handleRefresh() {
  orgSearch.id = undefined
  orgSearch.name = ''
}
let expandif = false
function expand() {
  expandif = !expandif
  handleQuery.value.forEach((row) => {
    tableRef.value.toggleRowExpansion(row, expandif) // true 展开，false 折叠
  })
}

// 删除
function deleteByIds() {

}

const deletedId = ref<Organization[]>([])

// 多选
function handleSelectionChange(val: Organization[]) {
  isDisabled.value = !val.length
  deletedId.value = val
}

// 修改用户信息
function modifyUser(id: number) {

}

// 获取组织信息
function getOrganization(id: number) {

}

// 获取权限信息
function getPermission(id: number) {

}
</script>

<template>
  <div>
    <el-form ref="queryFormRef" :inline="true" :model="orgSearch" class="form-inline">
      <el-form-item label="组织编码" prop="code">
        <el-input v-model="orgSearch.id" placeholder="组织编码" type="number" @input="handleFilterChange" />
      </el-form-item>
      <el-form-item label="组织名称" prop="name">
        <el-input v-model="orgSearch.name" placeholder="组织名称" @input="handleFilterChange" />
      </el-form-item>
      <el-form-item>
        <el-button type="warning" :icon="Refresh" @click="handleRefresh">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-form :inline="true" class="form-operate">
      <el-form-item>
        <el-button type="primary" size="small" plain @click="expand">
          展开/关闭
        </el-button>
        <el-button type="primary" size="small" plain @click="updateDialogVisible = true">
          新增
        </el-button>
        <el-button type="danger" size="small" plain :disabled="isDisabled" @click="deleteByIds">
          删除
        </el-button>
      </el-form-item>
    </el-form>
    <div class="table-container">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="handleQuery"
        style="width: 100%"
        row-key="id"
        border
        indent="20"
        :default-expand-all="shouldExpand"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="id"
          label="组织编号"
          width="200"
        />
        <el-table-column
          prop="name"
          label="组织名称"
          width="500"
          align="center"
        >
          <template #default="{ row }">
            <span v-html="highlightText(row.name)" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="modifyUser(scope.row.id)">
              修改
            </el-button>
            <el-button link type="primary" @click="getOrganization(scope.row.id)">
              组织
            </el-button>
            <el-button link type="primary" @click="getPermission(scope.row.id)">
              权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="update">
      <el-dialog
        v-model="updateDialogVisible"
        :title="updateDialogName"
        width="500px"
        draggable
        @close="refreshUser()"
      >
        <el-form
          ref="updateFormRef"
          :model="updateFormData"
          :rules="updateRules"
        >
          <el-form-item label="组织名称" prop="username">
            <el-input
              v-model="updateFormData.name"
            />
          </el-form-item>
          <div class="dialog-footer">
            <el-button @click="updateDialogVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="handleExecute(updateFormRef)">
              提交
            </el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>

</style>
